package com.leo.chapter07;

import javafx.concurrent.Task;

import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 *
 * @author xuexiaolei
 * @version 2017年10月16日
 */
public class Test {

    /**
     * 不可取消的任务在退出前恢复中断
     * @param queue
     * @return
     */
    public Task getNextTask(BlockingQueue<Task> queue){
        boolean interrupted = false;
        try {
            while (true){
                try {
                    return queue.take();
                } catch (InterruptedException e) {
                    interrupted = true;
                    //重新尝试
                }
            }
        } finally {
            if (interrupted) {Thread.currentThread().interrupt();}
        }
    }

    //通过Future取消任务
    public static ExecutorService exec;
    public static void timedRun(Runnable r, long timeout, TimeUnit unit) throws InterruptedException{
        Future task = exec.submit(r);
        try {
            task.get(timeout, unit);
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            //finally中取消它
        } finally {
            //如果任务已经结束，取消不受影响
            task.cancel(true);//如果任务正在运行，也将中断
        }
    }


    //只执行一次的任务
    public boolean checkMail(Set<String> hosts, long timeout, TimeUnit unit) throws InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();
        final AtomicBoolean hasNewMail = new AtomicBoolean(false);
        try {
            for (final String host : hosts) {
                exec.execute(new Runnable() {
                    @Override public void run() {
                        if (checkMail(host)) {hasNewMail.set(true);}
                    }
                });
            }
        } finally {
            exec.shutdown();
            exec.awaitTermination(timeout, unit);
        }
        return hasNewMail.get();
    }
    private boolean checkMail(String host) { return true; }
}
